<?php

namespace Biz\service\brand;

use Biz\model\brand\BrandUserPenalty as mBrandUserPenalty;
use Doraemon\model\AdmUserType;
use Doraemon\model\Member;
use Doraemon\model\Themis\Log as mThemisLog;
use Doraemon\cache\Forbid as cacheStopComment;
use Biz\service\Userpenalty\PenaltyStrategy;
use Biz\cache\brand\UserPenalty as cacheUserPenalty;
use Biz\model\brand\Brand as mBrand;
use Doraemon\tools\Log;


class BrandUserPenalty
{

    const TYPE_DELETE = "delete";

    const TYPE_ADD = "insert";

    const TYPE_UPDATE = "update";

    public static function syncSave($data)
    {
        if (in_array($data["type"], [self::TYPE_UPDATE, self::TYPE_ADD])) {
            Log::info('themis_log 获取数据', $data);
            $insert_data = $data['data'];
            $data = $insert_data;
            $uid = $data['uid'];
            if ($data['member_type'] == mBrandUserPenalty::AUTH_USER_BRAND) {
                self::saveDataByUid($uid, $data);
            }
        }
    }

    public static function saveDataByUid($uid, $data = [])
    {
        $penaltyInfo = mBrandUserPenalty::getListByUid($uid);
        $updateData = [];
        $updateData['uid'] = $uid;
        $info = AdmUserType::getByUid($uid);
        $updateData['quality'] = $info['quality'] ?: 0;
        $memberInfo = Member::getUserInfoByid('*', ['uid' => $uid]);
        $updateData['member_type'] = $memberInfo['type'];
        $updateData['is_forbidden'] = $memberInfo['status'] == Member::STATUS_BLOCKED ? mBrandUserPenalty::STATUS_BLOCKED : 0;
        $updateData['is_frozen'] = $memberInfo['status'] == Member::STATUS_FROZEN ? mBrandUserPenalty::STATUS_FROZEN : 0;
        cacheStopComment::getForbid($uid);
        $updateData['is_stop_comment'] = cacheStopComment::getForbid($uid) ? mBrandUserPenalty::STATUS_STOP_COMMENT : 0;
        if ($data['illegal_or_punish'] == mThemisLog::ACTION_ILLEGAL) {
            $updateData['last_violation_time'] = $data['addtime'];
        }
        if ($data['illegal_or_punish'] == mThemisLog::ACTION_PUNISH) {
            $updateData['last_admin_id'] = $data['admin_id'];
        }
        if ($penaltyInfo) {
            mBrandUserPenalty::updateByWhere(['uid' => $uid], $updateData);
        } else {
            mBrandUserPenalty::add($updateData);
        }
    }


    public static function getUidStatus($uid)
    {
        $result = [];
        if (empty($uid)) return [];
        $memberInfo = Member::getUserInfoByid('*', ['uid' => $uid]);
        if (empty($memberInfo)) return [];
        $info = AdmUserType::getByUid($uid);
        $result['quality'] = $info['quality'] ?: 0;
        $result['member_type'] = $memberInfo['type'];
        $result['is_forbidden'] = $memberInfo['status'] == Member::STATUS_BLOCKED ? mBrandUserPenalty::STATUS_BLOCKED : 0;
        $result['is_frozen'] = $memberInfo['status'] == Member::STATUS_FROZEN ? mBrandUserPenalty::STATUS_FROZEN : 0;
        return $result;
    }

    public static function getNewPunishCache($uid)
    {
        $brandId = mBrand::getBrandIdByUid($uid);
        if (empty($brandId)) return false;
        cacheUserPenalty::delBrand($brandId);
        $info = mThemisLog::getNewPunishByUid($uid);
        if ($info && is_array($info)) {
            cacheUserPenalty::addBrand($brandId, ['remark' => $info['remark'], 'link' => $info['preview_url']]);
        }
    }

    public static function cronCaclePunish()
    {
        $now = time();
        //清除今日惩罚
        $list = mThemisLog::getListByWhere(
            [
                'stoptime[<=]' => $now + 5,
                'stoptime[>]' => $now - 5,
                'illegal_or_punish' => mThemisLog::ACTION_PUNISH,
                'action_type' => [mThemisLog::ACTION_TYPE_ADD_B3, mThemisLog::ACTION_TYPE_ADD_B1, mThemisLog::ACTION_TYPE_ADD_B2, mThemisLog::ACTION_TYPE_ADD_COMMENT],
                'punish_status' => mThemisLog::IS_PUNISH,
            ]
        );

        //最近5s的解除惩罚
        if ($list && is_array($list)) {
            foreach ($list as $val) {
                $info = AdmUserType::getById($val['uid']);
                //如今的quality 更改了
                if ($info['quality'] != $val['quality'] && $info['action_type'] != mThemisLog::STATUS_STOP_COMMENT) {
                    mThemisLog::update(['punish_status' => mThemisLog::NOT_PUNISH], ['id' => $val['id']]);
                    return;
                }
                //之后还有其他的任务
                $nextInfo = mThemisLog::getListByWhere(['uid' => $val['uid'], 'addtime[>]' => $val['addtime'], 'action_type' => [mThemisLog::ACTION_TYPE_ADD_B3, mThemisLog::ACTION_TYPE_ADD_B1, mThemisLog::ACTION_TYPE_ADD_B2, mThemisLog::STATUS_STOP_COMMENT]]);
                if ($nextInfo) {
                    mThemisLog::update(['punish_status' => mThemisLog::NOT_PUNISH], ['id' => $val['id']]);
                    return;
                }

                $actionType = 0;
                $reamrk = '';
                switch ($val['action_type']) {
                    case mThemisLog::ACTION_TYPE_ADD_B1:
                        $punishType = PenaltyStrategy::TYPE_OPERATE_LOGO;
                        $punishData = [
                            'uid' => $val['uid'],
                            'quality' => 0,
                        ];
                        $reamrk = '系统解除B1';
                        $actionType = mThemisLog::ACTION_TYPE_DEL_B1;
                        break;
                    case mThemisLog::ACTION_TYPE_ADD_B2:
                        $punishType = PenaltyStrategy::TYPE_OPERATE_LOGO;
                        $punishData = [
                            'uid' => $val['uid'],
                            'quality' => 0,
                        ];
                        $reamrk = '系统解除B2';
                        $actionType = mThemisLog::ACTION_TYPE_DEL_B2;
                        break;
                    case mThemisLog::ACTION_TYPE_ADD_B3:
                        $punishType = PenaltyStrategy::TYPE_OPERATE_LOGO;
                        $punishData = [
                            'uid' => $val['uid'],
                            'quality' => 0,
                        ];
                        $reamrk = '系统解除B3';
                        $actionType = mThemisLog::ACTION_TYPE_DEL_B3;
                        break;
                    case mThemisLog::ACTION_TYPE_ADD_COMMENT:
//                       $punishType = PenaltyStrategy::TYPE_STOP_COMMENT;
//                       $punishData =[
//                           'uid' => $val['uid'] ,
//                           'quality' => 0,
//                       ];
                        $reamrk = '系统解除禁止评论';
                        $actionType = mThemisLog::ACTION_TYPE_DEL_COMMENT;
                        break;
                }
                if ($punishData) {
                    $result = PenaltyStrategy::cancle($punishType, $punishData);
                    if (!$result) {
                        Log::cacle_brand_punish_info('取消惩罚' . json_encode(['uid' => $val['uid'], 'id' => $val['id']]));
                        return;
                    }
                }
                if ($reamrk) {
                    $insertData = [];
                    $insertData['uid'] = $val['uid'];
                    $insertData['member_type'] = mThemisLog::AUTH_USER_BRAND;
                    $insertData['remark'] = $reamrk;
                    $insertData['addtime'] = time();
                    $insertData['illegal_or_punish'] = mThemisLog::ACTION_PUNISH;
                    $insertData['action_type'] = $actionType;
                }
                mThemisLog::add($insertData);
                mThemisLog::update(['punish_status' => mThemisLog::NOT_PUNISH], ['id' => $val['id']]);
            }
        }
    }


    public static function delOtherPunish($uid, $newPunish)
    {
        //寻找有效的punish
        $info = mThemisLog::getListByWhere(['uid' => $uid, 'punish_status' => mThemisLog::IS_PUNISH]);
        if (empty($info)) return;
        //之前的B级 操作全部失效

        if (in_array($newPunish['action_type'], [mThemisLog::ACTION_TYPE_ADD_B1, mThemisLog::ACTION_TYPE_ADD_B2, mThemisLog::ACTION_TYPE_ADD_B3])) {
            $bInfo = array_filter($info, function ($val) {
                if (in_array($val['action_type'], [mThemisLog::ACTION_TYPE_ADD_B1, mThemisLog::ACTION_TYPE_ADD_B2, mThemisLog::ACTION_TYPE_ADD_B3])) {
                    return true;
                }
                return false;
            });
            if ($bInfo && is_array($bInfo)) {
                mThemisLog::update(['punish_status' => mThemisLog::NOT_PUNISH], ['id' => array_column($bInfo, 'id')]);
            }
        }
        if ($newPunish['action_type'] == mThemisLog::ACTION_TYPE_ADD_COMMENT) {
            $stopInfo = array_filter($info, function ($val) {
                if ($val['action_type'] == mThemisLog::ACTION_TYPE_ADD_COMMENT) {
                    return true;
                }
                return false;
            });
            if ($stopInfo && is_array($stopInfo)) {
                mThemisLog::update(['punish_status' => mThemisLog::NOT_PUNISH], ['id' => array_column($stopInfo, 'id')]);
            }
        }
    }


}